package com.lagou.edu.mvcframework.pojo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

public class Handler {

    private Object controller;
    private Method method;
    private Pattern url;
    private Map<String, Integer> paramIndexMapping;

    public Handler(Object controller, Method method, Pattern url) {
        this.controller = controller;
        this.method = method;
        this.url = url;
        this.paramIndexMapping = parseParamIndexMapping(method.getParameters());
    }

    private Map<String, Integer> parseParamIndexMapping(Parameter[] parameters) {
        Map<String, Integer> pim = new HashMap<>(parameters.length);
        for (int i = 0; i < parameters.length; i++) {
            Parameter param = parameters[i];
            if (HttpServletRequest.class == param.getType() || HttpServletResponse.class == param.getType()) {
                pim.put(param.getType().getSimpleName(), i);
            }
            pim.put(param.getName(), i);
        }
        return pim;
    }

    public Object getController() {
        return controller;
    }

    public void setController(Object controller) {
        this.controller = controller;
    }

    public Method getMethod() {
        return method;
    }

    public void setMethod(Method method) {
        this.method = method;
    }

    public Pattern getUrl() {
        return url;
    }

    public void setUrl(Pattern url) {
        this.url = url;
    }

    public Map<String, Integer> getParamIndexMapping() {
        return paramIndexMapping;
    }

    public void setParamIndexMapping(Map<String, Integer> paramIndexMapping) {
        this.paramIndexMapping = paramIndexMapping;
    }
}
